package org.jypj.dev.controller;

import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.usermodel.WorkbookFactory;
import org.jypj.dev.dao.IGiveWorkDao;
import org.jypj.dev.dao.ITrainDao;
import org.jypj.dev.dao.IUserDao;
import org.jypj.dev.model.CodeData;
import org.jypj.dev.model.GiveWork;
import org.jypj.dev.model.Train;
import org.jypj.dev.model.User;
import org.jypj.dev.service.ICodeDataService;
import org.jypj.dev.util.ImportExcel;
import org.jypj.dev.util.StringUtil;
import org.jypj.dev.util.work.GiveWorkUtil;
import org.jypj.dev.vo.ImportVo;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.IOException;
import java.io.InputStream;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 派班数据
 */
@Controller
@RequestMapping("giveWorkImport")
public class GiveWorkImportController extends BaseController {


    @Resource
    private IGiveWorkDao giveWorkDao;

    @Resource
    private ITrainDao trainDao;

    @Resource
    private IUserDao userDao;

    @Resource
    private ICodeDataService codeDataService;

    private static Map<String, Train> trainCodeMap;//车次map

    private static Map<String, User> userMap;//用户map

    private static Set<String> trainNums;//车组号集合

    /**
     * xx导入
     *
     * @param file
     * @return
     */
    @RequestMapping("importGiveWorks.action")
    @ResponseBody
    public Map<String, Object> importGiveWorks(MultipartFile file) {
        Map<String, Object> dataMap = new HashMap<>();
        int code = 0;
        String msg = "";
        if (file == null) {
            code = -1;
            msg = "请选择文件";
        }
        try {
            ImportVo importVo = readGiveWorkExcel(file.getInputStream());
            if (!StringUtil.isEmpty(importVo.getErrorInfo())) {
                code = 1;
                msg = importVo.getErrorInfo();
            } else {
                //推送+保存
                List<GiveWork> giveWorks = importVo.getGiveWorks();
                GiveWorkUtil.remindWork(giveWorks);
                giveWorkDao.saveGiveWorks(giveWorks);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        dataMap.put("code", code);
        dataMap.put("msg", msg);
        return dataMap;
    }

    /**
     * 从Excel中读取教师信息
     *
     * @param in
     * @return
     */
    private ImportVo readGiveWorkExcel(InputStream in) throws IOException, InvalidFormatException {
        ImportVo importVo = new ImportVo();
        StringBuffer errorMsg = new StringBuffer();
        initCache();//初始化缓存数据
        Workbook workBook = WorkbookFactory.create(in);
        Sheet sheet = workBook.getSheetAt(0);
        for (int i = 1; i < sheet.getPhysicalNumberOfRows(); i++) {
            StringBuffer rowMsg = new StringBuffer();
            String trim = StringUtil.getLowUUID();
            GiveWork giveWork = new GiveWork(trim);
            for (int j = 1; j < 7; j++) {
                String param = ImportExcel.getCellValueByIndex(sheet, i, j);
                System.out.println(param);
                String cellMsg = checkParamAndSet(j, param, giveWork);
                if (StringUtil.isNotEmpty(cellMsg)) {
                    rowMsg.append("第" + (i + 1) + "行 " + cellMsg);
                }
            }
            if (StringUtil.isEmpty(rowMsg.toString())) {
                //说明这一行没有问题
                importVo.getGiveWorks().add(giveWork);
            } else {
                errorMsg.append(rowMsg);
            }
        }
        importVo.setErrorInfo(errorMsg.toString());
        return importVo;
    }

    /**
     * 初始化缓存数据
     */
    public void initCache() {
        Map<String, Object> queryMap = new HashMap<>();
        trainCodeMap = new HashMap<>();
        userMap = new HashMap<>();
        trainNums = new HashSet<>();
        //=======车次map
        List<Train> trains = trainDao.selectAllByMap(queryMap);
        for (Train train : trains) {
            trainCodeMap.put(train.getCode(), train);
        }
        //=======人员map
        List<User> users = userDao.selectAllByMap(queryMap);
        for (User user : users) {
            userMap.put(user.getUsername(), user);
        }
        //=======车组号集合
        List<CodeData> czhwh = codeDataService.selectAllByCode("czhwh");
        for (CodeData codeData : czhwh) {
            trainNums.add(codeData.getItemValue());
        }
    }

    /**
     * 核对并set参数
     *
     * @param col
     * @param param
     * @param giveWork
     * @return
     */
    public String checkParamAndSet(int col, String param, GiveWork giveWork) {
        StringBuffer errMsg = new StringBuffer("第" + (col + 1) + "列 \"" + param + "\" ");
        StringBuffer msg = new StringBuffer();
        if (StringUtil.isEmpty(param) && col != 6) {
            return msg.append("数据不能为空").toString();
        }
        SimpleDateFormat time = new SimpleDateFormat("HH:mm");
        SimpleDateFormat date = new SimpleDateFormat("yyyy-MM-dd");
        switch (col) {
            case 1://核对车次
                Train train = trainCodeMap.get(param);
                if (train != null) {
                    giveWork.setRoadId(train.getRoadId());
                } else {
                    msg.append("车次不存在");
                }
                break;
            case 2:
                if (trainNums.contains(param)) {
                    giveWork.setTrainNum(param);
                } else {
                    msg.append("车组号不存在");
                }
                break;
            case 3:
                User user = userMap.get(param);
                if (user != null) {
                    giveWork.setUserId(user.getId());
                    giveWork.setUserNum(user.getUserNum());
                } else {
                    msg.append("人员不存在");
                }
                break;
            case 4:
                String remindTime = param.trim();//提醒时间
                try {
                    time.parse(remindTime);
                    giveWork.setRemindTime(remindTime);
                } catch (ParseException e) {
                    msg.append("时间格式有误 正确格式：00:00");
                }
                break;
            case 5:
                String workDate = param.trim();
                try {
                    date.parse(workDate);
                    giveWork.setWorkDate(workDate);
                } catch (ParseException e) {
                    msg.append("日期格式有误 正确格式：2017-08-08");
                }
                break;
            case 6:
                giveWork.setRemindContent(param);
                break;
        }
        return StringUtil.isEmpty(msg.toString()) ? "" : errMsg.append(msg + "<br/>").toString();
    }

}
